<template>
  <div class="app-container">
    <div class="chat-container">
      <div class="chat-header">
        <h2>AI聊天室</h2>
        <el-button type="primary" size="mini" @click="createNewDialogue">新建对话</el-button>
      </div>

      <div class="chat-content" ref="chatContent">
        <div v-if="!dialogueId" class="welcome-container">
          <div class="welcome-title">您好，欢迎使用AI聊天系统</div>
          <div class="welcome-tips">我是一名智能聊天AI机器人，能回答各种问题，提供专业解答</div>
          <div class="quick-questions">
            <div class="quick-title">您可以尝试这些问题：</div>
            <div
              v-for="item in quickQuestions"
              :key="item.id"
              class="quick-item"
              @click="useQuickQuestion(item.tips)"
            >
              {{ item.tips }}
            </div>
          </div>
        </div>

        <div v-else class="messages-container">
          <div
            v-for="(message, index) in chatMessages"
            :key="index"
            :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
          >
            <div class="message-avatar">
              <img :src="message.role === 'user' ? userAvatar : aiAvatar" alt="avatar">
            </div>
            <div class="message-content">
              <div v-if="message.role === 'assistant'" v-html="formatMessage(message.content)"></div>
              <div v-else>{{ message.content }}</div>
            </div>
          </div>

          <div v-if="isTyping" class="message ai-message">
            <div class="message-avatar">
              <img :src="aiAvatar" alt="avatar">
            </div>
            <div class="message-content">
              <div v-html="formatMessage(currentAnswer)"></div>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
          v-model="inputMessage"
          :disabled="!isThisChatOver || !dialogueId"
          @keyup.ctrl.enter.native="sendMessage"
        ></el-input>
        <div class="input-actions">
          <el-button
            type="primary"
            :loading="!isThisChatOver"
            :disabled="!dialogueId || !inputMessage.trim()"
            @click="sendMessage"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { createDialogue, sendChatMessage, getChatHistory } from "@/api/ai/chatRoom";
import marked from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';

export default {
  name: "ChatRoom",
  data() {
    return {
      dialogueId: null,
      inputMessage: "",
      chatMessages: [],
      isTyping: false,
      isThisChatOver: true,
      currentAnswer: "",
      socketStatus: "closed",
      socket: null,
      overFlag: "THIS_CHAT_OVER",
      userAvatar: require("@/assets/logo/logo.png"),
      aiAvatar: require("@/assets/logo/logo.png"),
      quickQuestions: [
        { id: 1, tips: "请用Java帮我写个简单的冒泡排序" },
        { id: 2, tips: "如何提高编程效率" },
        { id: 3, tips: "简述Spring框架的核心特性" },
        { id: 4, tips: "人工智能的发展历程是什么" },
      ],
      newMessageQueue: [] // 消息队列
    };
  },
  created() {
    this.initMarked();
    this.checkUserLogin();
  },
  mounted() {
    if (this.isLoggedIn) {
      this.connectWebSocket();
    }
  },
  beforeDestroy() {
    this.closeWebSocket();
  },
  computed: {
    isLoggedIn() {
      return this.$store.getters.token != null && this.$store.getters.token !== '';
    }
  },
  methods: {
    initMarked() {
      // 设置marked配置，支持代码高亮
      marked.setOptions({
        renderer: new marked.Renderer(),
        highlight: function(code, language) {
          const validLanguage = hljs.getLanguage(language) ? language : 'plaintext';
          return hljs.highlight(validLanguage, code).value;
        },
        gfm: true,
        breaks: true,
      });
    },
    formatMessage(content) {
      if (!content) return '';
      return marked(content);
    },
    // 连接WebSocket
    connectWebSocket() {
      const token = this.$store.getters.token;
      if (!token) {
        this.$message.error("请先登录");
        return;
      }

      // 获取WebSocket URL，使用与微信小程序相同的连接方式
      const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      // 这里假设后端WebSocket接口与微信小程序共用一个
      const host = process.env.VUE_APP_BASE_API ? process.env.VUE_APP_BASE_API.replace(/^https?:\/\//, '') : window.location.host;
      const wsUrl = `${wsProtocol}//${host}/websocket/chat/${token}`;

      this.socket = new WebSocket(wsUrl);

      this.socket.onopen = () => {
        this.socketStatus = "connected";
        console.log("WebSocket连接成功");
      };

      this.socket.onclose = () => {
        this.socketStatus = "closed";
        console.log("WebSocket连接关闭");
        // 可以添加重连逻辑
        this.reconnectWebSocket();
      };

      this.socket.onerror = (error) => {
        console.error("WebSocket错误:", error);
        this.$message.error("WebSocket连接错误");
      };

      this.socket.onmessage = (event) => {
        if (event.data) {
          if (event.data === this.overFlag) {
            // 对话结束
            this.isThisChatOver = true;
            this.isTyping = false;

            // 将AI回答添加到消息列表
            if (this.currentAnswer) {
              this.chatMessages.push({
                role: 'assistant',
                content: this.currentAnswer
              });
            }
            this.currentAnswer = "";
            this.scrollToBottom();
          } else {
            // 采用小程序的方式处理流式响应
            this.isTyping = true;

            // 将新消息加入队列
            this.newMessageQueue.push(event.data);

            // 如果当前没有正在处理的消息，开始处理队列中的消息
            if (!this.isTyping || this.currentAnswer === "") {
              this.processNextMessage();
            } else {
              // 直接追加显示
              this.currentAnswer += event.data;
              this.scrollToBottom();
            }
          }
        }
      };
    },

    // 处理队列中的下一条消息
    processNextMessage() {
      if (this.newMessageQueue.length > 0) {
        const nextMessage = this.newMessageQueue.shift();
        this.currentAnswer += nextMessage;
        this.scrollToBottom();
      }
    },

    // 重连WebSocket
    reconnectWebSocket() {
      if (this.socketStatus === "closed") {
        setTimeout(() => {
          this.connectWebSocket();
        }, 3000); // 3秒后重连
      }
    },

    closeWebSocket() {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        this.socket.close();
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContent;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },

    // 创建新对话
    createNewDialogue() {
      createDialogue().then(response => {
        if (response.code === 200 && response.data) {
          this.dialogueId = response.data;
          this.chatMessages = [];
          this.currentAnswer = "";
          this.isTyping = false;
          this.isThisChatOver = true;
          this.$message.success("成功创建新对话");
        } else {
          this.$message.error("创建对话失败");
        }
      }).catch(error => {
        console.error("创建对话出错:", error);
        this.$message.error("创建对话出错");
      });
    },

    // 加载历史消息
    loadChatHistory() {
      if (!this.dialogueId) return;

      getChatHistory(this.dialogueId).then(response => {
        if (response.code === 200 && response.data) {
          // 转换消息格式
          this.chatMessages = response.data.map(msg => ({
            role: msg.role,
            content: msg.content
          }));
          this.scrollToBottom();
        }
      }).catch(error => {
        console.error("获取聊天历史失败:", error);
      });
    },

    // 使用快速提问
    useQuickQuestion(question) {
      this.inputMessage = question;
      if (!this.dialogueId) {
        this.createNewDialogue();
        // 等待创建对话完成后再发送消息
        setTimeout(() => {
          if (this.dialogueId) {
            this.sendMessage();
          }
        }, 500);
      } else {
        this.sendMessage();
      }
    },

    // 发送消息
    sendMessage() {
      if (!this.inputMessage.trim() || !this.isThisChatOver) {
        return;
      }

      if (!this.dialogueId) {
        this.createNewDialogue();
        return;
      }

      const message = this.inputMessage;
      this.chatMessages.push({
        role: 'user',
        content: message
      });
      this.inputMessage = "";
      this.isThisChatOver = false;
      this.scrollToBottom();

      // 发送消息到服务器
      sendChatMessage({
        dialogueId: this.dialogueId,
        content: message
      }).then(() => {
        // 消息发送成功，等待WebSocket接收回复
      }).catch(error => {
        console.error("发送消息出错:", error);
        this.$message.error("发送消息失败");
        this.isThisChatOver = true;
      });
    },
    // 检查用户登录状态
    checkUserLogin() {
      if (!this.isLoggedIn) {
        this.$modal.alert('请先登录后再使用AI聊天功能', '提示', {
          confirmButtonText: '去登录',
          callback: () => {
            this.$router.push('/login');
          }
        });
      }
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 130px);
  background-color: #f9f9f9;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #eaeaea;
  background-color: #fff;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.welcome-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.welcome-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #409EFF;
}

.welcome-tips {
  font-size: 16px;
  color: #606266;
  margin-bottom: 30px;
}

.quick-questions {
  width: 80%;
  max-width: 600px;
}

.quick-title {
  font-size: 16px;
  margin-bottom: 15px;
  color: #606266;
}

.quick-item {
  background-color: #ecf5ff;
  color: #409EFF;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.quick-item:hover {
  background-color: #409EFF;
  color: #fff;
}

.messages-container {
  display: flex;
  flex-direction: column;
}

.message {
  display: flex;
  margin-bottom: 20px;
  max-width: 90%;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  margin: 0 10px;
  flex-shrink: 0;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.message-content {
  padding: 10px 15px;
  border-radius: 4px;
  word-break: break-word;
  overflow-wrap: break-word;
  max-width: calc(100% - 60px);
}

.user-message .message-content {
  background-color: #409EFF;
  color: #fff;
  border-top-right-radius: 0;
}

.ai-message .message-content {
  background-color: #fff;
  color: #606266;
  border-top-left-radius: 0;
  box-shadow: 0 2px 4px rgba(0,0,0,.1);
}

.ai-message .message-content :deep(pre) {
  background-color: #f6f8fa;
  border-radius: 4px;
  padding: 10px;
  overflow-x: auto;
  margin: 10px 0;
}

.ai-message .message-content :deep(code) {
  font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
}

.chat-input {
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid #eaeaea;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
